<?php
$db = Db::getInstance();
$query = sprintf("SELECT * FROM Topic WHERE id='%s'", $db->real_escape_string($_GET['id']));
$result = $db->query($query);
if(!$result){
	throw new Exception($db->error);
}
if($result->num_rows==0){
	View::display('message', array('message'=> 'ไม่พบคำภามนี้'));
	exit();
}
$topic = $result->fetch_assoc();
$topic['account'] = Account::instance()->getOne($topic['accountId']);

if(!Authenticate::isLogin() || $topic['accountId'] != Authenticate::getId()){
	View::display('message', array('message'=> 'คุณไม่ได้รับสิทธิ์ในการเข้าถึงคำถามนี้'));
	exit();
}

if($_SERVER['REQUEST_METHOD']=='GET'){
	$replies = array();
	$query = sprintf("SELECT * FROM Reply WHERE topicId='%s'", $db->real_escape_string($topic['id']));
	$result = $db->query($query);
	while($row = $result->fetch_assoc()){
		if($row['author']=='account')
			$row['owner'] = Account::instance()->getOne($row['accountId']);
		else if($row['author']=='technic')
			$row['owner'] = array('name'=> 'ฝ่ายเทคนิค', 'email'=> 'pla2dc@gmail.com');
		$replies[] = $row;
	}
	View::display('user/topic', array('topic'=> $topic, 'replies'=> $replies));
    Topic::instance()->edit($_GET['id'], array('readNew'=> 0));
}
else if($_SERVER['REQUEST_METHOD']=='POST'){
	$db = Db::getInstance();
	$db->autocommit(false);
	try {
		if(empty($_POST['detail'])){
			throw new Exception('empty detail');
		}
		$query = sprintf("INSERT INTO Reply(detail, topicId, author, accountId) VALUES('%s','%s','account','%s')",
			$db->real_escape_string($_POST['detail']),
			$db->real_escape_string($_GET['id']),
			Authenticate::getId()
		);
		if(!$db->query($query)){
			throw new Exception($db->error);
		}
		$query = sprintf("UPDATE Topic SET modifyTime='%s' WHERE id='%s'", date('Y-m-d H:i:s'), $db->real_escape_string($_GET['id']));
		if(!$db->query($query)){
			throw new Exception($db->error);
		}
		$db->commit();
	} catch(Exception $ex) {
		$db->rollback();
		throw $ex;
	}
	header("Location: old.php?page=user/topic&id={$_GET['id']}");
}
else if($_SERVER['REQUEST_METHOD']=='PUT'){
	parse_str(file_get_contents("php://input"), $formData);
    try{
        $id = $formData['id'];
        $set = $formData;
        unset($set['id']);
        Topic::instance()->edit($id, array('status'=> $formData['status']));
        echo json_encode(array('success'=> true));
    }
    catch (Exception $e){
        echo json_encode(array('success'=> false));
        throw $e;
    }
}